package com.test;

import lombok.extern.slf4j.Slf4j;
import okhttp3.*;

import java.io.File;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static java.util.Objects.isNull;
import static okhttp3.MediaType.parse;
import static okhttp3.RequestBody.create;

@Slf4j
public class HttpUtils {
    private static final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder()
            .connectTimeout(50, TimeUnit.SECONDS)
            .writeTimeout(50, TimeUnit.SECONDS)
            .readTimeout(50, TimeUnit.SECONDS)
            .build();

    private static Interceptor buildInterceptor() {
        return chain -> chain.proceed(chain.request().newBuilder()
                .header("Accept", "application/json")
                .build());
    }

    private static OkHttpClient createClientByInterceptor(Interceptor interceptor) {
        return HTTP_CLIENT.newBuilder()
                .addInterceptor(interceptor)
                .build();
    }


    public static String getJsonString(String host, String url, Map<String, Object> params) throws IOException {
        FormBody.Builder form = new FormBody.Builder();
        for (Map.Entry<String, Object> e : params.entrySet()) {
            if (isNull(e.getValue())) {
                continue;
            }

            form.add(e.getKey(), e.getValue().toString());
        }

        Request request = buildRequest(host, url, form.build());

        Response response = createClientByInterceptor(buildInterceptor())
                .newCall(request)
                .execute();

        String string = response.body().string();
        return string;
    }

    /**
     * 构建 okhttp 请求
     * @param host
     * @param url
     * @param body
     * @return
     */
    private static Request buildRequest(String host, String url, RequestBody body) {
        return new Request.Builder()
                .url(new HttpUrl.Builder()
                        .scheme("https")
                        .host(host)
                        .addPathSegments(url)
                        .build())
                .post(body)
                .build();
    }
}
